/**
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY. 
 * See the GNU General Public License for more details.
 * 
 * Copyright (C) 2011 CellObject.net
 */
package net.cellobject.javacodeformatter.view;

import net.cellobject.javacodeformatter.model.FormatterManager;
import net.cellobject.javacodeformatter.model.FormatterManagerEvent;
import net.cellobject.javacodeformatter.model.FormatterManagerListener;

import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.widgets.Display;

class FormatterViewContentProvider implements IStructuredContentProvider, FormatterManagerListener {
	private TableViewer viewer;

	private FormatterManager manager;

	public void inputChanged(final Viewer viewer, final Object oldInput, final Object newInput) {
		this.viewer = (TableViewer)viewer;
		if (manager != null) {
			manager.removeFavoritesManagerListener(this);
		}
		manager = (FormatterManager)newInput;
		if (manager != null) {
			manager.addFavoritesManagerListener(this);
		}
	}

	public void dispose() {
	}

	public Object[] getElements(final Object parent) {
		return manager.getFavorites();
	}

	public void favoritesChanged(final FormatterManagerEvent event) {
		// If this is the UI thread, then make the change.
		if (Display.getCurrent() != null) {
			updateViewer(event);
			return;
		}
		// otherwise, redirect to execute on the UI thread.
		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
				updateViewer(event);
			}
		});
	}

	private void updateViewer(final FormatterManagerEvent event) {
		// Use the setRedraw method to reduce flicker
		// when adding or removing multiple items in a table.
		viewer.getTable().setRedraw(false);
		try {
			viewer.remove(event.getItemsRemoved());
			viewer.add(event.getItemsAdded());
		} finally {
			viewer.getTable().setRedraw(true);
		}
	}
}
